#include "file_manager.h"
#include "utils.h"

FileManager::FileManager(int carCount) : _carCount(carCount) {}

void FileManager::saveToFile(std::string dirName) {
    if (!folderExists(dirName)) {
        if (!createFolder(dirName)) {
            cout << "创建文件夹失败, 退出！！" << endl;
            return;
        }
    } else {
        cout << dirName << "文件夹已经存在，将覆盖其中的文件" << endl;
    }

    for (size_t i = 0; i < _cars.size(); i++) {
        std::string fName = dirName + "/car" + std::to_string(i + 1) + ".yaml";
        auto car = _cars[i];
        cout << "正在保存第" << i + 1 << "个小车的信息:" << fName << endl;
        car.save(fName);
    }
    cout << "保存完成" << endl;
}

void FileManager::setCars(std::vector<SmartCar>& cars) {
    _cars = cars;
}

void FileManager::loadFromFile(std::string dirName) {
    for (size_t i = 0; i < _carCount; i++) {
        std::string fName = dirName + "/car" + std::to_string(i + 1) + ".yaml";
        cout << "正在读取第" << i + 1 << "个小车的信息:" << fName << endl;
        YAML::Node config = YAML::LoadFile(fName);
        SmartCar car;
        deserializeSmartCar(config, car);
        _carsFromFile.emplace_back(car);
    }
    return;
}

std::vector<SmartCar>& FileManager::getSmartCars() {
    return _carsFromFile;
}

void FileManager::deserializeSmartCar(YAML::Node& node, SmartCar& car) {
    car.setID(node["id"].as<std::string>());
    car.chasis = node["Chasis"].as<Chasis>();
    car.tire = node["Tire"].as<Tire>();
    car.agx = node["AGX"].as<AGX>();
    car.camera = node["StereoCamera"].as<StereoCamera>();
    car.lidar = node["Lidar"].as<Lidar>();
    car.gyro = node["Gyroscope"].as<Gyroscope>();
    car.lcd = node["LCD"].as<LCD>();
    car.battery = node["Battery"].as<Battery>();
    car.stu = node["Student"].as<Student>();
}
